// src/api/ai/index.ts
import { apiClient } from '../config';
import { ChatRequest, ChatResponse, ChatCompletionRequest, ChatCompletionResponse } from './types';

// API接口地址
const AI_API_ENDPOINTS = {
  CHAT: '/ai/chat',
  COMPLETION: '/ai/completion',
  TRANSLATE: '/ai/translate',
  SUMMARIZE: '/ai/summarize'
};

/**
 * 聊天对话接口
 * @param data 聊天请求数据
 */
export const chatWithAI = async (data: ChatRequest): Promise<ChatResponse> => {
  try {
    const response = await apiClient.post<ChatResponse>(AI_API_ENDPOINTS.CHAT, data);
    return response;
  } catch (error) {
    throw new Error(`聊天接口调用失败: ${error}`);
  }
};

/**
 * 文本补全接口
 * @param data 补全请求数据
 */
export const completeText = async (data: ChatCompletionRequest): Promise<ChatCompletionResponse> => {
  try {
    const response = await apiClient.post<ChatCompletionResponse>(AI_API_ENDPOINTS.COMPLETION, data);
    return response;
  } catch (error) {
    throw new Error(`文本补全接口调用失败: ${error}`);
  }
};

/**
 * 文本翻译接口
 * @param text 待翻译文本
 * @param targetLanguage 目标语言
 */
export const translateText = async (text: string, targetLanguage: string): Promise<string> => {
  try {
    const response = await apiClient.post<{ translated_text: string }>(AI_API_ENDPOINTS.TRANSLATE, {
      text,
      target_language: targetLanguage
    });
    return response.translated_text;
  } catch (error) {
    throw new Error(`翻译接口调用失败: ${error}`);
  }
};

/**
 * 文本摘要接口
 * @param text 待摘要文本
 * @param maxLength 最大长度
 */
export const summarizeText = async (text: string, maxLength?: number): Promise<string> => {
  try {
    const response = await apiClient.post<{ summary: string }>(AI_API_ENDPOINTS.SUMMARIZE, {
      text,
      max_length: maxLength
    });
    return response.summary;
  } catch (error) {
    throw new Error(`摘要接口调用失败: ${error}`);
  }
};

/**
 * 简单的AI问答接口
 * @param question 用户问题
 */
export const askAI = async (question: string): Promise<string> => {
  try {
    const data: ChatRequest = {
      messages: [
        { role: 'user', content: question }
      ],
      model: 'gpt-3.5-turbo',
      temperature: 0.7
    };
    
    const response = await chatWithAI(data);
    return response.choices[0].message.content;
  } catch (error) {
    console.error('AI问答失败:', error);
    throw new Error('AI助手暂时无法回答您的问题，请稍后再试');
  }
};